from rest_framework.viewsets import GenericViewSet
from mixins import MyListModelMixin, MyDestroyModelMixin, MyCreateModelMixin, MyUpdateModelMixin
from format import menus_to_tree2
from response import APIResponse
from permission import MyPermissions
from .serializers import MenuSerializers
from status import *
from auth import JwtTokenAuthentication
from .models import Menus


class MenuViews(MyListModelMixin, MyDestroyModelMixin, MyCreateModelMixin, MyUpdateModelMixin, GenericViewSet):
    queryset = Menus.objects.filter(is_deleted=False).all().order_by("-id")
    serializer_class = MenuSerializers
    permission_classes = [MyPermissions]
    authentication_classes = [JwtTokenAuthentication]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        data = menus_to_tree2([dict(item) for item in serializer.data])
        return APIResponse(code=SUCCESS, msg="获取成功", data=data)

    def perform_destroy(self, instance):
        instance.is_deleted = True
        query_all = Menus.objects.filter(parent_id=instance.id).all()
        query_obj_list = []
        for query in query_all:
            query.is_deleted = True
            query_obj_list.append(query)
        Menus.objects.bulk_update(query_obj_list, ["is_deleted"], batch_size=len(query_all))
        instance.save()

    def perform_create(self, serializer):
        menu_pid = serializer.validated_data.pop("menu_pid")
        serializer.save(parent_id=menu_pid)
